//
//  NavigationGestureEnabler.swift
//  xgwjinterconnection
//  启用手势返回
//  Created by WangWeiShuo on 2025/8/22.
//

import SwiftUI

// 自定义导航控制器包装器，用于启用手势返回
struct NavigationGestureEnabler: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewController {
        UIViewController()
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        // 查找导航控制器并启用手势
        DispatchQueue.main.async {
            if let navController = uiViewController.navigationController {
                navController.interactivePopGestureRecognizer?.isEnabled = true
                navController.interactivePopGestureRecognizer?.delegate = context.coordinator
            }
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    class Coordinator: NSObject, UIGestureRecognizerDelegate {
        // 允许手势与其他手势共存
        func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
            return true
        }
        
        // 防止在根视图触发手势导致崩溃
//        func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
//            guard let navController = gestureRecognizer.view?.inputAccessoryViewController?.navigationController else {
//                return false
//            }
//            return navController.viewControllers.count > 1
//        }
    }
}

// 扩展View，添加便捷修饰符
extension View {
    func enableSwipeBackGesture() -> some View {
        self.background(NavigationGestureEnabler())
    }
}
